import Koa from 'koa'
import userRouter from './router/userRouter'
import totalTime from './middleware/totalTime'
import { mongoGo } from './mongo'
import cors from 'koa2-cors'

const app = new Koa()

app.use(
  cors({
    origin: function (ctx) {
      if (ctx.url === '/test') {
        return false
      }
      console.log('ctx.headers.origin', ctx.headers.origin)
      return '*'
      // return ctx.headers.origin // 就是前端的location.origin : 'http://localhost:8080'
    },
    // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    // maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
    allowHeaders: [
      'Content-Type',
      'Content-Length',
      'Authorization',
      'Accept',
      'X-Requested-With',
    ],
  })
)

app.use(totalTime) // 每次请求耗时
app.use(userRouter.routes()).use(userRouter.allowedMethods()) // 路由

app.listen(3000, () => {
  console.log('server is running on http://localhost:3000')
})

mongoGo()
